package com.baixiaowen.xiaoaointerview.Java编程功底篇.五种手写排序.选择排序;

import com.baixiaowen.xiaoaointerview.Java编程功底篇.五种手写排序.Helper;
import com.baixiaowen.xiaoaointerview.Java编程功底篇.五种手写排序.IMutableSorter;

/**
 * 选择排序
 *
 * @author Baixiaowen
 */
public class SelectionSort implements IMutableSorter {

    @Override
    public void sort(int[] A) {
        // 2 2 1 1
        for (int i = A.length - 1; i >= 0 ; i--) {

            // 0 - A[i] 左闭右开
            int j = maxIndex(A, 0, i + 1);
            Helper.swap(A, i, j);
        }
    }

    private static int maxIndex(int[] A, int i, int j) {
        int max = Integer.MIN_VALUE;

        int maxIndex = j - 1;
        for (int k = j - 1; k >= i; k--) {
            if (max < A[k]) {
                max = A[k];
                maxIndex = k;
            }
        }
        return maxIndex;
    }
}
